package cn.ivicar.app.resource.customer;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.servlet.RequestScoped;

import cn.com.carsmart.exception.BadRequestException;
import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.exception.InternalErrorException;
import cn.com.carsmart.exception.NotAuthorizedException;
import cn.com.carsmart.exception.util.ExceptionResponseBuilder;
import cn.com.carsmart.sae.SaeUtils;
import cn.com.carsmart.ws.util.CacheUtil;
import cn.ivicar.app.controller.sae.CurrentUtil;
import cn.ivicar.passport.controller.CaptchaController;
import net.sf.json.JSONObject;

@Path("captcha")
@RequestScoped
public class CaptchaReource {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(CaptchaReource.class);

	@Inject
	private CaptchaController captchaController;

	/**
	 * 获取手机验证码
	 * 
	 * @param jsonObject
	 * @return
	 */
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response getCaptcha(JSONObject jsonObject) {
		try {
			if (jsonObject.isEmpty() || jsonObject.isNullObject()) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}

			String mobile = jsonObject.optString("mobile", "");
			String bizType = jsonObject.optString("bizType", "");

			Long customerId = null;
			boolean isOauth = SaeUtils.getContext().getSubject().isAuthenticated();
			if (isOauth) {
				customerId = CurrentUtil.getCustomerId();
			}
			captchaController.getCaptcha(customerId, mobile, bizType);

			return CacheUtil.noCache(Response.ok()).build();
		} catch (NotAuthorizedException e) {
			LOGGER.info("无权访问 :", e);
			return ExceptionResponseBuilder.build(e);
		} catch (BadRequestException e) {
			LOGGER.info("获取验证码非法请求:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("获取验证码异常", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("获取验证码失败,失败原因：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("获取验证码程序异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}
}